Telegram Group & Telegram Channel
✔️ Задача. Что выведет на консоль этот пример на C#?


using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
var funcs = new List<Func<int>>();

// Первая группа лямбд
for (int i = 0; i < 4; i++)
{
funcs.Add(() => i * i);
}

Console.Write("Squares: ");
foreach (var f in funcs)
Console.Write(f() + " ");

Console.WriteLine();

// Вторая группа лямбд с копией переменной
funcs.Clear();
for (int i = 0; i < 4; i++)
{
int j = i;
funcs.Add(() => j * j);
}

Console.Write("SquaresWithCopy: ");
foreach (var f in funcs)
Console.Write(f() + " ");
}
}

Ответ:
Squares: 16 16 16 16
SquaresWithCopy: 0 1 4 9

Объяснение
Первая группа лямбд
Лямбды захватывают переменную i по ссылке. К моменту, когда мы их вызываем в foreach, цикл уже завершился, поэтому i == 4. Каждая лямбда вычисляет 4 * 4 → 16.

Вторая группа лямбд
Внутри цикла для каждого значения i создаётся новая локальная переменная j, и лямбда захватывает именно её. При первой итерации j = 0, при второй j = 1 и т. д. Поэтому j * j даёт 0, 1, 4, 9 соответственно.

Такой приём (захват локальной копии переменной) позволяет избежать «одинообразного» результата и сохранить значение каждой итерации.
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/csharp_ci/1346
Create:
Last Update:

✔️ Задача. Что выведет на консоль этот пример на C#?


using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
var funcs = new List<Func<int>>();

// Первая группа лямбд
for (int i = 0; i < 4; i++)
{
funcs.Add(() => i * i);
}

Console.Write("Squares: ");
foreach (var f in funcs)
Console.Write(f() + " ");

Console.WriteLine();

// Вторая группа лямбд с копией переменной
funcs.Clear();
for (int i = 0; i < 4; i++)
{
int j = i;
funcs.Add(() => j * j);
}

Console.Write("SquaresWithCopy: ");
foreach (var f in funcs)
Console.Write(f() + " ");
}
}

Ответ:
Squares: 16 16 16 16
SquaresWithCopy: 0 1 4 9

Объяснение
Первая группа лямбд
Лямбды захватывают переменную i по ссылке. К моменту, когда мы их вызываем в foreach, цикл уже завершился, поэтому i == 4. Каждая лямбда вычисляет 4 * 4 → 16.

Вторая группа лямбд
Внутри цикла для каждого значения i создаётся новая локальная переменная j, и лямбда захватывает именно её. При первой итерации j = 0, при второй j = 1 и т. д. Поэтому j * j даёт 0, 1, 4, 9 соответственно.

Такой приём (захват локальной копии переменной) позволяет избежать «одинообразного» результата и сохранить значение каждой итерации.

BY C# (C Sharp) programming


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/csharp_ci/1346

View MORE
Open in Telegram


C C Sharp programming Telegram | DID YOU KNOW?

Date: |

Mr. Durov launched Telegram in late 2013 with his brother, Nikolai, just months before he was pushed out of VK, the Russian social-media platform he founded. Mr. Durov pitched his new app—funded with the proceeds from the VK sale—less as a business than as a way for people to send messages while avoiding government surveillance and censorship.

That growth environment will include rising inflation and interest rates. Those upward shifts naturally accompany healthy growth periods as the demand for resources, products and services rise. Importantly, the Federal Reserve has laid out the rationale for not interfering with that natural growth transition.It's not exactly a fad, but there is a widespread willingness to pay up for a growth story. Classic fundamental analysis takes a back seat. Even negative earnings are ignored. In fact, positive earnings seem to be a limiting measure, producing the question, "Is that all you've got?" The preference is a vision of untold riches when the exciting story plays out as expected.

C C Sharp programming from hk


Telegram C# (C Sharp) programming
FROM USA